<template>
  <div class="container">
    <div class="post-comment">
      <div class="title">{{ postDetail.title }}</div>
      <div class="comment">
        <u-comment
            page
            :config="config"
            @submit="submit"
            @like="like"
            relative-time
        >
        </u-comment>
      </div>
    </div>
    <div class="relation-recommend">
      <span style="font-size:18px;">相关推荐</span>
      <div class="list" v-for="post in  recommendPostList" :key="post.id">
        <img :src="post.coverImage" height="50" width="50" alt="封面">
        <div class="base">
          <div>
            {{ post.title.substring(0,8) }}...
          </div>
          <div class="bottom">
            <span style="font-size:13px;color:#949494">{{ post.accessNumber }}人读过</span>
            <tiny-tag
                type="info"
                effect="dark"
                style="margin-left:50px;cursor: pointer"
                @click="toPostDetail(post.id)"
            >
              <book-open theme="outline" size="18" style="margin-right:5px;" fill="#fff" :strokeWidth="2"/>
              阅读
            </tiny-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onUnmounted, ref} from "vue";
import {dayjs} from "undraw-ui";
import {Modal, Tag as TinyTag} from "@opentiny/vue";
import emoji from "../utils/emoji.js";
import {BookOpen} from '@icon-park/vue-next'
import {useRoute, useRouter} from "vue-router";
import request from '../utils/request.js'
import {userName} from "../config/index.js";


const route = useRoute()
const router = useRouter()
const postId = route.params.postId
const config = ref({
  user: {
    id: 0,
    username: '',
    avatar: '',
    // 评论id数组 根据用户uid来获取对应点赞评论id,然后加入到数组中返回
    // likeIds: [1, 2, 3],
  },
  emoji: emoji,
  comments: [],
  total: 10
})
let temp_id = 100
const recommendPostList = ref([])
const currentUser = localStorage.getItem(userName) ? JSON.parse(localStorage.getItem(userName)) : null
const postDetail = ref({})
const pageNum = ref(1)
const pageSize = ref(150)
const seconds = ref(0)


// 跳转帖子详情页
const toPostDetail = postId => {
  const {href} = router.resolve(`/post/detail/${postId}`)
  window.open(href,'_blank')
}

// 查询帖子相关推荐
const queryRecommendPostList = () => {
  // 判断用户是否登录
  request.get(`/api/contents/posts/recommend/${currentUser.id}`).then(res => {
    if (res.code === 1) {
      recommendPostList.value = res.data
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryRecommendPostList()

// 提交评论事件
const submit = ({content, parentId, files, finish, reply}) => {
  let str = '提交评论:' + content + ';\t父id: ' + parentId + ';\t图片:' + files + ';\t被回复评论:'
  // console.log(str, reply)

  temp_id += 1
  const comment = {
    id: temp_id,
    parentId: parentId,
    uid: config.value.user.id,
    content: content,
    likes: 0,
    createTime: dayjs().subtract(5, 'seconds').toString(),
    user: {
      username: config.value.user.username,
      avatar: config.value.user.avatar,
      // homeLink: `/${(temp_id)}`
    },
    reply: null
  }
  // 保存参数 默认回复的帖子
  let param = {
    postId,
    content: comment.content,
    userId: config.value.user.id,
    replyId: postId,
    replyType: 0
  }
  if (parentId) { // 回复的评论
    const rep = comment.content.match(/<[^>]*>([^<]*)$/)
    param.replyType = 1
    param.content = rep[1].trim()
    // param.parentId = postId
    param.replyId = reply ? reply.uid : null
    param.parentId = parentId
  }

  setTimeout(() => {
    finish(comment)
    // 保存评论
    request.post('/api/comments/posts', param).then(res => {
      if (res.code === 1) {
        Modal.message({message: '评论成功', status: 'success'})
      }
    })
  }, 200)
}

// 点赞按钮事件 将评论id返回后端判断是否点赞，然后在处理点赞状态
const like = (id, finish) => {
  console.log('点赞: ' + id)
  setTimeout(() => {
    finish()
  }, 200)
}

// 查询评论
const queryPostComment = () => {
  const temp = {
    postId,
    pageParam: {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
  }
  request.post('/api/comments/posts/page', temp).then(res => {
    if (res.code === 1) {
      config.value.user.id = currentUser.id
      config.value.user.username = currentUser.nickname
      config.value.user.avatar = currentUser.avatar
      // 统计当前用户的点赞
      config.value.user.likeIds = res.data.records.map(v => {
        if ((currentUser.id === v.userId) && (v.starNum > 0)) {
          return v.id
        }
      })

      // 处理评论文章的评论
      let tempComments = []
      res.data.records.forEach(comment => {
        let tempComment = {
          user: {
            username: '',
            avatar: '',
            homeLink: ''
          }
        }
        if (comment.replyType === 0) { // 评论文章
          tempComment.id = comment.id
          tempComment.parentId = null
          tempComment.uid = comment.userId
          tempComment.content = comment.content
          tempComment.createTime = comment.createTime.split(' ')[0]
          tempComment.likes = comment.starNum
          tempComment.user.username = comment.nickname
          tempComment.user.avatar = comment.avatar
          tempComment.user.homeLink = '/1'

          tempComments.push(tempComment)
        }
      })

      // 处理回复
      const childrenComments = res.data.records.filter(v => v.replyType === 1) // 取出回复评论
      tempComments.forEach(comment => { // 遍历评论
        comment.reply = {
          total: 0,
          list: [],
        }
        childrenComments.forEach(child => {
          if (child.parentId === comment.id) {
            let tempComment = {
              user: {
                username: '',
                avatar: '',
                homeLink: ''
              }
            }
            tempComment.id = child.id
            tempComment.parentId = child.parentId
            tempComment.uid = child.userId
            tempComment.createTime = child.createTime.split(' ')[0]
            tempComment.likes = child.starNum
            tempComment.user.username = child.nickname
            tempComment.user.avatar = child.avatar
            tempComment.user.homeLink = '/1'

            if (child.replyId === comment.uid) {
              tempComment.content = child.content
            } else {
              const children = childrenComments.find(v => v.userId === child.replyId)
              tempComment.content = "回复 <span style=\"color: var(--u-color-success-dark-2);\">@ " + children.nickname + ":</span>" + child.content
            }

            comment.reply.list.push(tempComment)
          }
        })
        comment.reply.total = comment.reply.list.length
      })
      config.value.comments = tempComments
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryPostComment()

// 查询帖子
const queryPostAndUserStatus = () => {
  request.get(`/api/contents/posts/${postId}`).then(res => {
    if (res.code === 1) {
      postDetail.value = res.data
      document.title = res.data.title
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryPostAndUserStatus()

// 定义定时器
const timer = () => {
  setInterval(() => {
    seconds.value++
  }, 1000)
}
timer()

onUnmounted(() => {
  clearInterval(timer)
  if (currentUser) {
    if (seconds.value >= 2) {
      const tmp = {
        postId: Number(postId),
        userId: currentUser.id,
        collectStatus: 0,
        starStatus: 0,
        commentStatus: 0, // 统一传未评论，在后端查询评论列表判断是否评论
      }
      request.post('/api/contents/posts/users', tmp).then(res => {
        if (res.code !== 1)
          Modal.message({message: res.message, status: 'error'})
      })
    }
  }
})

</script>

<style lang="less" scoped>

.container {
  .relation-recommend {
    .list {
      .base {
        margin-left: 20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-bottom: 15px;
      }

      display: flex;
    }

    width: 20%;
    height: 100%;
    margin-left: 20px;
    border: 1px solid #ddd;
    border-radius: 5px;
    position: sticky;
    top: 0;
    padding: 10px;
  }

  .post-comment {
    .title {
      border-bottom: 1px solid #ddd;
      overflow-x: auto;
      height: 30px;
      position: sticky;
      top: 0;
      z-index: 999;
      background-color: #f2f3f5;
      line-height: 30px;
      padding-left: 10px;
    }

    width: 65%;
  }

  display: flex;
}

</style>
